package cn.stylefeng.guns.modular.fi.controller;

import cn.hutool.http.HttpRequest;
import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
import cn.stylefeng.guns.core.util.DateUtil2;
import cn.stylefeng.guns.modular.basic.entity.BasicCustomer;
import cn.stylefeng.guns.modular.basic.entity.BasicOperate;
import cn.stylefeng.guns.modular.basic.entity.BasicPutgoods;
import cn.stylefeng.guns.modular.basic.model.params.BasicAddressParam;
import cn.stylefeng.guns.modular.basic.model.params.BasicGoodsParam;
import cn.stylefeng.guns.modular.basic.model.params.BasicPutgoodsParam;
import cn.stylefeng.guns.modular.basic.model.params.BasicXlbOauth2tokenParam;
import cn.stylefeng.guns.modular.basic.model.result.BasicAddressResult;
import cn.stylefeng.guns.modular.basic.model.result.BasicGoodsResult;
import cn.stylefeng.guns.modular.basic.model.result.BasicPutgoodsResult;
import cn.stylefeng.guns.modular.basic.model.result.BasicXlbOauth2tokenResult;
import cn.stylefeng.guns.modular.basic.service.BasicCustomerService;
import cn.stylefeng.guns.modular.basic.service.BasicOperateService;
import cn.stylefeng.guns.modular.basic.service.BasicXlbOauth2tokenService;
import cn.stylefeng.guns.modular.fi.entity.FiOrderAsyc;
import cn.stylefeng.guns.modular.fi.model.params.FiOrderAsycParam;
import cn.stylefeng.guns.modular.fi.service.FiOrderAsycService;
import cn.stylefeng.guns.modular.order.entity.OrderTransport;
import cn.stylefeng.guns.modular.order.entity.StorageTaskXlb;
import cn.stylefeng.guns.modular.order.model.params.OrderTransportDetailedParam;
import cn.stylefeng.guns.modular.order.model.params.OrderTransportParam;
import cn.stylefeng.guns.modular.order.model.result.OrderTransportResult;
import cn.stylefeng.guns.modular.order.service.OrderTransportService;
import cn.stylefeng.guns.sys.modular.system.entity.User;
import cn.stylefeng.roses.core.base.controller.BaseController;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.guns.sys.modular.system.service.UserService;
import cn.stylefeng.roses.core.util.ToolUtil;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


/**
 * 拣货单拉取控制器
 *
 * @author zhangzh
 * @Date 2025-01-19 09:17:32
 */
@Controller
@RequestMapping("/fiOrderAsyc")
public class FiOrderAsycController extends BaseController {

    private String PREFIX = "/fi/fiOrderAsyc";

    @Autowired
    private FiOrderAsycService fiOrderAsycService;

    @Autowired
    private UserService userService;

    @Value("${hxl.api.url}")
    private String hxlApiUrl;

    @Autowired
    private BasicOperateService basicOperateService;

    @Autowired
    private BasicCustomerService basicCustomerService;

    @Autowired
    private BasicXlbOauth2tokenService basicXlbOauth2tokenService;

    @Autowired
    private OrderTransportService orderTransportService;

    /**
     * 跳转到主页面
     *
     * @author zhangzh
     * @Date 2025-01-19
     */
    @RequestMapping("")
    public String index(Model model) {
        User user = userService.getcurrentUser();
        //查询可选择分公司
        model.addAttribute("basicOperatelist", basicOperateService.findAvailableList(user.getDeptId(),user.getDeliverId(),user.getOperateId()));
        return PREFIX + "/fiOrderAsyc.html";
    }

    /**
     * 新增页面
     *
     * @author zhangzh
     * @Date 2025-01-19
     */
    @RequestMapping("/add")
    public String add() {
        return PREFIX + "/fiOrderAsyc_add.html";
    }

    /**
     * 编辑页面
     *
     * @author zhangzh
     * @Date 2025-01-19
     */
    @RequestMapping("/edit")
    public String edit() {
        return PREFIX + "/fiOrderAsyc_edit.html";
    }

    /**
     * 新增接口
     *
     * @author zhangzh
     * @Date 2025-01-19
     */
    @RequestMapping("/addItem")
    @ResponseBody
    public ResponseData addItem(FiOrderAsycParam fiOrderAsycParam) {
        this.fiOrderAsycService.add(fiOrderAsycParam);
        return ResponseData.success();
    }

    /**
     * 编辑接口
     *
     * @author zhangzh
     * @Date 2025-01-19
     */
    @RequestMapping("/editItem")
    @ResponseBody
    public ResponseData editItem(FiOrderAsycParam fiOrderAsycParam) {
        this.fiOrderAsycService.update(fiOrderAsycParam);
        return ResponseData.success();
    }

    /**
     * 删除接口
     *
     * @author zhangzh
     * @Date 2025-01-19
     */
    @RequestMapping("/delete")
    @ResponseBody
    public ResponseData delete(FiOrderAsycParam fiOrderAsycParam) {
        this.fiOrderAsycService.delete(fiOrderAsycParam);
        return ResponseData.success();
    }


    @RequestMapping("/replaceOne")
    @ResponseBody
    public ResponseData replaceOne(FiOrderAsycParam fiOrderAsycParam) {
        this.fiOrderAsycService.replaceOne(fiOrderAsycParam);
        return ResponseData.success();
    }

    /**
     * 查看详情接口
     *
     * @author zhangzh
     * @Date 2025-01-19
     */
    @RequestMapping("/detail")
    @ResponseBody
    public ResponseData detail(FiOrderAsycParam fiOrderAsycParam) {
        FiOrderAsyc detail = this.fiOrderAsycService.getById(fiOrderAsycParam.getOrderNumber());
        return ResponseData.success(detail);
    }

    /**
     * 查询列表
     *
     * @author zhangzh
     * @Date 2025-01-19
     */
    @ResponseBody
    @RequestMapping("/list")
    public LayuiPageInfo list(FiOrderAsycParam fiOrderAsycParam,String condition ) {
        return this.fiOrderAsycService.findPageBySpec(fiOrderAsycParam,condition);
    }


    /**
     * 拉取新零帮拣货任务页面
     */
    @RequestMapping("/topullxlbStoragetask")
    public String topullxlbStoragetask() {
        return PREFIX + "/pullxlbStoragetask.html";
    }

    /**
     * 拉取新零帮拣货任务
     * @author zhucx
     * @Date 2023-09-30
     */
    @RequestMapping("/pullxlbStoragetask")
    @ResponseBody
    @Transactional(rollbackFor = Exception.class,timeout = 6000)
    public ResponseData pullxlbStoragetask(String modified_begin,String modified_end, Integer customerId) {
        String url = this.hxlApiUrl+"/hxl.open.wms.pickOrder.find";
//        String url = "https://hxl-api.xlbsoft.com/api/hxl.open.wms.pickOrder.find";
        List<String> pick_finish_time = new ArrayList<String>();
        pick_finish_time.add(modified_begin);
        pick_finish_time.add(modified_end);
        BasicCustomer r = basicCustomerService.getById(customerId);

        if(ToolUtil.isEmpty(r.getStoreIdXlb())) {
            return ResponseData.error("请维护新零帮发货门店id");
        }
        if(ToolUtil.isEmpty(r.getGsnumber())) {
            return ResponseData.error("请维护新零帮公司号");
        }
        User user = userService.getcurrentUser();

        BasicXlbOauth2tokenParam oauth2tokenParam = new BasicXlbOauth2tokenParam();
        oauth2tokenParam.setDeliverId(r.getDeliverId());
        oauth2tokenParam.setGsnumber(r.getGsnumber());
        BasicXlbOauth2tokenResult oauth2tokenResult = basicXlbOauth2tokenService.findBySpec(oauth2tokenParam);
        if(oauth2tokenResult != null) {
            if (ToolUtil.isNotEmpty(oauth2tokenResult.getOauth2TokenXlb())) {
                JSONObject json = new JSONObject();
                json.put("store_id", r.getStoreIdXlb());
				if(ToolUtil.isNotEmpty(r.getNeedCheck())&&r.getNeedCheck().equals("1")) {
					json.put("check_finish_time", pick_finish_time);
				} else {
					json.put("pick_finish_time", pick_finish_time);
				}
//                json.put("pick_finish_time", pick_finish_time);
                String post = HttpRequest.post(url)
                        .header("Authorization", "bearer " + oauth2tokenResult.getOauth2TokenXlb()).body(json.toString()).execute().body();
//				System.out.println("================json："+json+"========================");
//				System.out.println("================post："+post+"========================");
                JSONObject jsonObject = new JSONObject(post);
                if (jsonObject.get("code").toString().equals("0")) {
                    List<FiOrderAsyc> fiOrderAsycs = new ArrayList<FiOrderAsyc>();
                    JSONArray jsonArray = new JSONArray(jsonObject.get("data").toString());
                    FiOrderAsyc fiOrderAsyc;
                    for (Object object : jsonArray) {
                        fiOrderAsyc = new FiOrderAsyc();

                        JSONObject jsonObject2 = new JSONObject(object.toString());
                        String fid = jsonObject2.get("fid").toString();
                        if (ToolUtil.isNotEmpty(fid) && !fid.equals("null")) {//单据号
                            fiOrderAsyc.setOrderNumber(fid);
                        } else {
                            continue;
                        }

                        String client_id = jsonObject2.get("client_id").toString();
                        if (ToolUtil.isNotEmpty(client_id)) {//收货客户id
                            fiOrderAsyc.setGetUnitid(Long.valueOf(client_id));
                        }

                        String client_name = jsonObject2.get("client_name").toString();
                        if (ToolUtil.isNotEmpty(client_name) && !client_name.equals("null")) {//客户名称
                            fiOrderAsyc.setGetUnit(client_name);
                        } else {
                            continue;
                        }

//                        String item_count = jsonObject2.get("item_count").toString();
//                        if (ToolUtil.isNotEmpty(item_count)&&!item_count.equals("null")){//商品数
//                            fiOrderAsyc.setGoodsNum(item_count);
//                        } else {
//                            continue;
//                        }

                        String quantity = jsonObject2.get("quantity").toString();
                        if (ToolUtil.isNotEmpty(quantity) && !quantity.equals("null")) {//应拣数量
                            fiOrderAsyc.setTotalnum(new BigDecimal(quantity));
                        } else {
                            continue;
                        }

                        String volume = jsonObject2.get("volume").toString();
                        if (ToolUtil.isNotEmpty(volume)) {//体积
                            fiOrderAsyc.setTotalvolume(volume);
                        }
                        String demolition = jsonObject2.get("demolition").toString();
                        String delivery_date = jsonObject2.get("delivery_date").toString();
                        if (ToolUtil.isNotEmpty(delivery_date)) {//配送日期
                            fiOrderAsyc.setSetMentiontime(delivery_date);
                        }

                        if (ToolUtil.isNotEmpty(demolition) && demolition.equals("true")) {
                            String box_count = jsonObject2.get("box_count").toString();
                            if (ToolUtil.isNotEmpty(box_count) && !box_count.equals("null")) {//封箱拆零数
                                fiOrderAsyc.setPieceNumber(Integer.valueOf(box_count));
                            }
                        }

                        //创建人
                        fiOrderAsyc.setCreateUser(user.getUserId());
                        fiOrderAsyc.setCreateName(user.getName());
                        //创建时间
                        fiOrderAsyc.setCreateTime(new Date());
                        //项目信息
                        fiOrderAsyc.setOperateId(Long.valueOf(r.getCustomerOperateId()));
                        fiOrderAsyc.setOperateName(r.getCustomerOperateName());

                        OrderTransport orderTransport = this.orderTransportService.lambdaQuery()
                                .eq(OrderTransport::getOrderNumber, fid)
                                .ne(OrderTransport::getTstate, "作废")
                                .one();
                        if(ToolUtil.isNotEmpty(orderTransport)){
                            fiOrderAsyc.setTransportNumber(orderTransport.getTransportNumber());
                        }
                        fiOrderAsycs.add(fiOrderAsyc);
                    }
                    if (fiOrderAsycs.size() > 0) {
                        this.fiOrderAsycService.saveOrUpdateBatch(fiOrderAsycs);
                    }
                }else{
                    return ResponseData.error(jsonObject.get("code").toString());
                }
            }
        }
            return ResponseData.success();
    }
}


